package com.ruoyi.common.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cassandra.CassandraProperties;

import java.io.IOException;

public class WeChatSubscribeMessageSenderUtils {

    @Value("${wechat.app-id}")
    private static  String APP_ID ;

    @Value("${wechat.app-secret}")
    private static  String APP_SECRET;


    public static void sendMessage(String openId, String tempId, String message){
        try {
            String accessToken = getAccessToken();
            String openid = openId;
            String templateId = tempId;
            JsonObject data = new JsonObject();
            JsonObject keyword1 = new JsonObject();
            keyword1.addProperty("value", message);
            data.add("keyword1", keyword1);
            sendSubscribeMessage(accessToken, openid, templateId, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static String getAccessToken() throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
        return jsonObject.get("access_token").getAsString();
    }

    private static void sendSubscribeMessage(String accessToken, String openid, String templateId, JsonObject data) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        JsonObject message = new JsonObject();
        message.addProperty("touser", openid);
        message.addProperty("template_id", templateId);
        message.add("data", data);

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), message.toString());
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
}
